import * as fs from 'fs';
import * as path from 'path';

// 生成唯一的 ID
function generateId(): string {
  return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}


// 创建通用响应结构
function createResponseSchema(successData: any, errorCodes: number[] = [400, 401, 403, 404, 500]) {
  const responses: any[] = [
    {
      id: generateId(),
      code: 200,
      name: "成功",
      headers: [],
      jsonSchema: {
        type: "object",
        properties: {
          code: {
            type: "integer",
            examples: [200]
          },
          msg: {
            type: "string",
            examples: ["成功"]
          },
          data: successData,
          requestId: {
            type: "string",
            description: "请求ID"
          }
        },
        required: ["code", "msg", "data", "requestId"],
        "x-apifox-orders": ["code", "msg", "data", "requestId"]
      },
      description: "请求成功",
      contentType: "json",
      mediaType: ""
    }
  ];

  // 添加错误响应
  const errorMessages: Record<number, string> = {
    400: "请求参数错误",
    401: "未授权，请先登录",
    403: "权限不足",
    404: "资源不存在",
    500: "服务器内部错误"
  };

  errorCodes.forEach(code => {
    responses.push({
      id: generateId(),
      code,
      name: errorMessages[code] || "错误",
      headers: [],
      jsonSchema: {
        type: "object",
        properties: {
          code: {
            type: "integer",
            examples: [code]
          },
          msg: {
            type: "string",
            examples: [errorMessages[code] || "错误"]
          },
          data: {
            type: "object"
          },
          requestId: {
            type: "string"
          }
        },
        "x-apifox-orders": ["code", "msg", "data", "requestId"]
      },
      description: errorMessages[code] || "错误",
      contentType: "json",
      mediaType: ""
    });
  });

  return responses;
}

// 创建 API 项
function createApiItem(name: string, method: string, path: string, requestBody: any, successData: any, auth: any = {}, description: string = "") {
  return {
    name,
    api: {
      id: generateId(),
      method: method.toLowerCase(),
      path,
      parameters: {
        query: [],
        path: [],
        cookie: [],
        header: []
      },
      auth,
      securityScheme: {},
      commonParameters: {
        query: [],
        body: [],
        cookie: [],
        header: []
      },
      responses: createResponseSchema(successData),
      responseExamples: [],
      requestBody: requestBody ? {
        type: "application/json",
        parameters: [],
        jsonSchema: {
          type: "object",
          properties: requestBody.properties || {},
          required: requestBody.required || [],
          "x-apifox-orders": requestBody.orders || []
        },
        examples: requestBody.examples || [],
        mediaType: "",
        oasExtensions: "",
        required: requestBody.required && requestBody.required.length > 0,
        additionalContentTypes: []
      } : undefined,
      description,
      tags: [],
      status: "released",
      serverId: "",
      operationId: "",
      sourceUrl: "",
      ordering: 0,
      cases: [],
      mocks: [],
      customApiFields: "{}",
      advancedSettings: {
        disabledSystemHeaders: {}
      },
      mockScript: {},
      codeSamples: [],
      commonResponseStatus: {},
      responseChildren: [],
      visibility: "INHERITED",
      moduleId: 6509018,
      oasExtensions: "",
      type: "http",
      preProcessors: [],
      postProcessors: [],
      inheritPostProcessors: {},
      inheritPreProcessors: {}
    }
  };
}

// 创建文件夹
function createFolder(name: string, description: string, items: any[], id: number) {
  return {
    name,
    id,
    auth: {},
    securityScheme: {},
    parentId: 0,
    serverId: "",
    description,
    identityPattern: {
      httpApi: {
        type: "inherit",
        bodyType: "",
        fields: []
      }
    },
    shareSettings: {},
    visibility: "INHERITED",
    moduleId: 6509018,
    preProcessors: [{
      id: "inheritProcessors",
      type: "inheritProcessors",
      data: {}
    }],
    postProcessors: [{
      id: "inheritProcessors",
      type: "inheritProcessors",
      data: {}
    }],
    inheritPostProcessors: {},
    inheritPreProcessors: {},
    items
  };
}

// 生成完整的 Apifox JSON
function generateApifoxJson() {
  const rootId = 70628974;
  let folderIdCounter = 70629716;

  // 认证管理
  const authFolder = createFolder("认证管理", "登录、登出、查询个人信息", [
    createApiItem(
      "用户登录",
      "post",
      "/api/auth/login",
      {
        properties: {
          username: { type: "string", description: "用户名", examples: ["admin"] },
          password: { type: "string", description: "密码", examples: ["Admin123"] }
        },
        required: ["username", "password"],
        orders: ["username", "password"],
        examples: [{
          mediaType: "application/json",
          value: JSON.stringify({ username: "admin", password: "Admin123" }, null, 2)
        }]
      },
      {
        type: "object",
        properties: {
          user: {
            type: "object",
            properties: {
              id: { type: "string", description: "用户ID" },
              username: { type: "string", description: "用户名" },
              nickname: { type: "string", description: "昵称" },
              email: { type: "string", description: "邮箱" },
              phone: { type: "string", description: "手机号" },
              is_admin: { type: "integer", description: "是否管理员" },
              status: { type: "integer", description: "状态" }
            }
          },
          token: { type: "string", description: "访问令牌" }
        }
      },
      {},
      "用户登录接口，返回访问令牌和用户信息"
    ),
    createApiItem(
      "用户登出",
      "post",
      "/api/auth/logout",
      {
        properties: {
          token: { type: "string", description: "令牌（可选，可从Header获取）" }
        },
        required: [],
        orders: ["token"],
        examples: [{
          mediaType: "application/json",
          value: "{}"
        }]
      },
      {
        type: "object",
        properties: {
          message: { type: "string", examples: ["登出成功"] }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "用户登出，撤销访问令牌"
    ),
    createApiItem(
      "获取当前用户信息",
      "post",
      "/api/auth/current",
      {
        properties: {},
        required: [],
        orders: [],
        examples: [{
          mediaType: "application/json",
          value: "{}"
        }]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          username: { type: "string" },
          nickname: { type: "string" },
          email: { type: "string" },
          phone: { type: "string" },
          is_admin: { type: "integer" },
          status: { type: "integer" },
          permissions: {
            type: "array",
            items: {
              type: "object",
              properties: {
                id: { type: "string" },
                name: { type: "string" },
                code: { type: "string" },
                description: { type: "string" }
              }
            }
          }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "获取当前登录用户信息"
    )
  ], folderIdCounter++);

  // 用户管理
  const userFolder = createFolder("用户管理", "登录用户的增删改查（需要管理员权限）", [
    createApiItem(
      "创建用户",
      "post",
      "/api/users/create",
      {
        properties: {
          username: { type: "string", description: "用户名" },
          password: { type: "string", description: "密码" },
          nickname: { type: "string", description: "昵称" },
          email: { type: "string", description: "邮箱" },
          phone: { type: "string", description: "手机号" },
          permission_ids: { type: "array", items: { type: "string" }, description: "权限ID列表" }
        },
        required: ["username", "password"],
        orders: ["username", "password", "nickname", "email", "phone", "permission_ids"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          username: { type: "string" },
          nickname: { type: "string" },
          email: { type: "string" },
          phone: { type: "string" },
          is_admin: { type: "integer" },
          status: { type: "integer" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "创建新用户（仅管理员）"
    ),
    createApiItem(
      "更新用户",
      "post",
      "/api/users/update",
      {
        properties: {
          id: { type: "string", description: "用户ID" },
          nickname: { type: "string", description: "昵称" },
          email: { type: "string", description: "邮箱" },
          phone: { type: "string", description: "手机号" },
          status: { type: "integer", description: "状态" },
          permission_ids: { type: "array", items: { type: "string" }, description: "权限ID列表" }
        },
        required: ["id"],
        orders: ["id", "nickname", "email", "phone", "status", "permission_ids"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          username: { type: "string" },
          nickname: { type: "string" },
          email: { type: "string" },
          phone: { type: "string" },
          is_admin: { type: "integer" },
          status: { type: "integer" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "更新用户信息"
    ),
    createApiItem(
      "删除用户",
      "post",
      "/api/users/delete",
      {
        properties: {
          id: { type: "string", description: "用户ID" }
        },
        required: ["id"],
        orders: ["id"]
      },
      {
        type: "object",
        properties: {
          message: { type: "string", examples: ["删除成功"] }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "删除用户（仅管理员）"
    ),
    createApiItem(
      "查询用户列表",
      "post",
      "/api/users/list",
      {
        properties: {
          page: { type: "integer", description: "页码", examples: [1] },
          pageSize: { type: "integer", description: "每页数量", examples: [10] },
          username: { type: "string", description: "用户名（模糊搜索）" },
          status: { type: "integer", description: "状态" }
        },
        required: [],
        orders: ["page", "pageSize", "username", "status"]
      },
      {
        type: "object",
        properties: {
          list: {
            type: "array",
            items: {
              type: "object",
              properties: {
                id: { type: "string" },
                username: { type: "string" },
                nickname: { type: "string" },
                email: { type: "string" },
                phone: { type: "string" },
                is_admin: { type: "integer" },
                status: { type: "integer" }
              }
            }
          },
          total: { type: "integer" },
          page: { type: "integer" },
          pageSize: { type: "integer" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "查询用户列表（仅管理员）"
    ),
    createApiItem(
      "查询用户详情",
      "post",
      "/api/users/detail",
      {
        properties: {
          id: { type: "string", description: "用户ID" }
        },
        required: ["id"],
        orders: ["id"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          username: { type: "string" },
          nickname: { type: "string" },
          email: { type: "string" },
          phone: { type: "string" },
          is_admin: { type: "integer" },
          status: { type: "integer" },
          permissions: {
            type: "array",
            items: {
              type: "object",
              properties: {
                id: { type: "string" },
                name: { type: "string" },
                code: { type: "string" },
                description: { type: "string" }
              }
            }
          }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "查询用户详情"
    )
  ], folderIdCounter++);

  // 权限管理
  const permissionFolder = createFolder("权限管理", "权限的增删改查（需要管理员权限）", [
    createApiItem(
      "创建权限",
      "post",
      "/api/permissions/create",
      {
        properties: {
          name: { type: "string", description: "权限名称" },
          code: { type: "string", description: "权限代码" },
          description: { type: "string", description: "权限描述" }
        },
        required: ["name", "code"],
        orders: ["name", "code", "description"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          name: { type: "string" },
          code: { type: "string" },
          description: { type: "string" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "创建权限"
    ),
    createApiItem(
      "更新权限",
      "post",
      "/api/permissions/update",
      {
        properties: {
          id: { type: "string", description: "权限ID" },
          name: { type: "string", description: "权限名称" },
          code: { type: "string", description: "权限代码" },
          description: { type: "string", description: "权限描述" }
        },
        required: ["id"],
        orders: ["id", "name", "code", "description"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          name: { type: "string" },
          code: { type: "string" },
          description: { type: "string" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "更新权限"
    ),
    createApiItem(
      "删除权限",
      "post",
      "/api/permissions/delete",
      {
        properties: {
          id: { type: "string", description: "权限ID" }
        },
        required: ["id"],
        orders: ["id"]
      },
      {
        type: "object",
        properties: {
          message: { type: "string", examples: ["删除成功"] }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "删除权限"
    ),
    createApiItem(
      "查询权限列表",
      "post",
      "/api/permissions/list",
      {
        properties: {
          page: { type: "integer", description: "页码", examples: [1] },
          pageSize: { type: "integer", description: "每页数量", examples: [10] },
          name: { type: "string", description: "权限名称（模糊搜索）" },
          code: { type: "string", description: "权限代码（模糊搜索）" }
        },
        required: [],
        orders: ["page", "pageSize", "name", "code"]
      },
      {
        type: "object",
        properties: {
          list: {
            type: "array",
            items: {
              type: "object",
              properties: {
                id: { type: "string" },
                name: { type: "string" },
                code: { type: "string" },
                description: { type: "string" }
              }
            }
          },
          total: { type: "integer" },
          page: { type: "integer" },
          pageSize: { type: "integer" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "查询权限列表"
    ),
    createApiItem(
      "查询权限详情",
      "post",
      "/api/permissions/detail",
      {
        properties: {
          id: { type: "string", description: "权限ID" }
        },
        required: ["id"],
        orders: ["id"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          name: { type: "string" },
          code: { type: "string" },
          description: { type: "string" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "查询权限详情"
    )
  ], folderIdCounter++);

  // 会员管理
  const memberFolder = createFolder("会员管理", "会员的增删改查", [
    createApiItem(
      "创建会员",
      "post",
      "/api/members/create",
      {
        properties: {
          name: { type: "string", description: "会员姓名" },
          phone: { type: "string", description: "手机号" },
          email: { type: "string", description: "邮箱" },
          gender: { type: "integer", description: "性别：0-未知，1-男，2-女" },
          birthday: { type: "string", description: "生日" },
          address: { type: "string", description: "地址" },
          level_id: { type: "string", description: "会员等级ID" }
        },
        required: ["name"],
        orders: ["name", "phone", "email", "gender", "birthday", "address", "level_id"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          user_id: { type: "string" },
          name: { type: "string" },
          phone: { type: "string" },
          email: { type: "string" },
          gender: { type: "integer" },
          birthday: { type: "string" },
          address: { type: "string" },
          status: { type: "integer" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "创建会员"
    ),
    createApiItem(
      "更新会员",
      "post",
      "/api/members/update",
      {
        properties: {
          id: { type: "string", description: "会员ID" },
          name: { type: "string", description: "会员姓名" },
          phone: { type: "string", description: "手机号" },
          email: { type: "string", description: "邮箱" },
          gender: { type: "integer", description: "性别" },
          birthday: { type: "string", description: "生日" },
          address: { type: "string", description: "地址" },
          status: { type: "integer", description: "状态" },
          level_id: { type: "string", description: "会员等级ID" }
        },
        required: ["id"],
        orders: ["id", "name", "phone", "email", "gender", "birthday", "address", "status", "level_id"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          user_id: { type: "string" },
          name: { type: "string" },
          phone: { type: "string" },
          email: { type: "string" },
          gender: { type: "integer" },
          birthday: { type: "string" },
          address: { type: "string" },
          status: { type: "integer" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "更新会员信息"
    ),
    createApiItem(
      "删除会员",
      "post",
      "/api/members/delete",
      {
        properties: {
          id: { type: "string", description: "会员ID" }
        },
        required: ["id"],
        orders: ["id"]
      },
      {
        type: "object",
        properties: {
          message: { type: "string", examples: ["删除成功"] }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "删除会员"
    ),
    createApiItem(
      "查询会员列表",
      "post",
      "/api/members/list",
      {
        properties: {
          page: { type: "integer", description: "页码", examples: [1] },
          pageSize: { type: "integer", description: "每页数量", examples: [10] },
          name: { type: "string", description: "会员姓名（模糊搜索）" },
          phone: { type: "string", description: "手机号（模糊搜索）" },
          status: { type: "integer", description: "状态" }
        },
        required: [],
        orders: ["page", "pageSize", "name", "phone", "status"]
      },
      {
        type: "object",
        properties: {
          list: {
            type: "array",
            items: {
              type: "object",
              properties: {
                id: { type: "string" },
                user_id: { type: "string" },
                name: { type: "string" },
                phone: { type: "string" },
                email: { type: "string" },
                gender: { type: "integer" },
                birthday: { type: "string" },
                address: { type: "string" },
                status: { type: "integer" },
                level_id: { type: "string" }
              }
            }
          },
          total: { type: "integer" },
          page: { type: "integer" },
          pageSize: { type: "integer" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "查询会员列表"
    ),
    createApiItem(
      "查询会员详情",
      "post",
      "/api/members/detail",
      {
        properties: {
          id: { type: "string", description: "会员ID" }
        },
        required: ["id"],
        orders: ["id"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          user_id: { type: "string" },
          name: { type: "string" },
          phone: { type: "string" },
          email: { type: "string" },
          gender: { type: "integer" },
          birthday: { type: "string" },
          address: { type: "string" },
          status: { type: "integer" },
          level_id: { type: "string" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "查询会员详情"
    )
  ], folderIdCounter++);

  // 会员等级管理
  const memberLevelFolder = createFolder("会员等级管理", "会员等级的增删改查", [
    createApiItem(
      "创建会员等级",
      "post",
      "/api/member-levels/create",
      {
        properties: {
          name: { type: "string", description: "等级名称" },
          level: { type: "integer", description: "等级数字" },
          description: { type: "string", description: "等级描述" }
        },
        required: ["name", "level"],
        orders: ["name", "level", "description"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          name: { type: "string" },
          level: { type: "integer" },
          description: { type: "string" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "创建会员等级"
    ),
    createApiItem(
      "更新会员等级",
      "post",
      "/api/member-levels/update",
      {
        properties: {
          id: { type: "string", description: "等级ID" },
          name: { type: "string", description: "等级名称" },
          level: { type: "integer", description: "等级数字" },
          description: { type: "string", description: "等级描述" }
        },
        required: ["id"],
        orders: ["id", "name", "level", "description"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          name: { type: "string" },
          level: { type: "integer" },
          description: { type: "string" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "更新会员等级"
    ),
    createApiItem(
      "删除会员等级",
      "post",
      "/api/member-levels/delete",
      {
        properties: {
          id: { type: "string", description: "等级ID" }
        },
        required: ["id"],
        orders: ["id"]
      },
      {
        type: "object",
        properties: {
          message: { type: "string", examples: ["删除成功"] }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "删除会员等级"
    ),
    createApiItem(
      "查询会员等级列表",
      "post",
      "/api/member-levels/list",
      {
        properties: {
          name: { type: "string", description: "等级名称（模糊搜索）" }
        },
        required: [],
        orders: ["name"]
      },
      {
        type: "array",
        items: {
          type: "object",
          properties: {
            id: { type: "string" },
            name: { type: "string" },
            level: { type: "integer" },
            description: { type: "string" }
          }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "查询会员等级列表"
    ),
    createApiItem(
      "查询会员等级详情",
      "post",
      "/api/member-levels/detail",
      {
        properties: {
          id: { type: "string", description: "等级ID" }
        },
        required: ["id"],
        orders: ["id"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          name: { type: "string" },
          level: { type: "integer" },
          description: { type: "string" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "查询会员等级详情"
    )
  ], folderIdCounter++);

  // 备份管理
  const backupFolder = createFolder("备份管理", "数据库备份管理（需要管理员权限）", [
    createApiItem(
      "创建备份",
      "post",
      "/api/backups/create",
      {
        properties: {
          description: { type: "string", description: "备份描述" }
        },
        required: [],
        orders: ["description"]
      },
      {
        type: "object",
        properties: {
          id: { type: "string" },
          filename: { type: "string" },
          filepath: { type: "string" },
          size: { type: "integer" },
          description: { type: "string" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "创建数据库备份"
    ),
    createApiItem(
      "删除备份",
      "post",
      "/api/backups/delete",
      {
        properties: {
          id: { type: "string", description: "备份ID" }
        },
        required: ["id"],
        orders: ["id"]
      },
      {
        type: "object",
        properties: {
          message: { type: "string", examples: ["删除成功"] }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "删除备份"
    ),
    createApiItem(
      "查询备份列表",
      "post",
      "/api/backups/list",
      {
        properties: {
          page: { type: "integer", description: "页码", examples: [1] },
          pageSize: { type: "integer", description: "每页数量", examples: [10] }
        },
        required: [],
        orders: ["page", "pageSize"]
      },
      {
        type: "object",
        properties: {
          list: {
            type: "array",
            items: {
              type: "object",
              properties: {
                id: { type: "string" },
                filename: { type: "string" },
                filepath: { type: "string" },
                size: { type: "integer" },
                description: { type: "string" }
              }
            }
          },
          total: { type: "integer" },
          page: { type: "integer" },
          pageSize: { type: "integer" }
        }
      },
      {
        type: "bearer",
        bearer: {
          token: "{{Authorization}}"
        }
      },
      "查询备份列表"
    )
  ], folderIdCounter++);

  // 健康检查
  const healthFolder = createFolder("健康检查", "服务健康检查", [
    createApiItem(
      "健康检查",
      "post",
      "/api/health/check",
      {
        properties: {},
        required: [],
        orders: [],
        examples: [{
          mediaType: "application/json",
          value: "{}"
        }]
      },
      {
        type: "object",
        properties: {
          status: { type: "string", examples: ["healthy", "unhealthy"] },
          checks: {
            type: "object",
            properties: {
              koa: { type: "boolean" },
              mysql: { type: "boolean" },
              redis: { type: "boolean" }
            }
          },
          timestamp: { type: "string" }
        }
      },
      {},
      "检查 Koa、MySQL、Redis 服务状态"
    )
  ], folderIdCounter++);

  // 构建完整的 JSON
  const apifoxJson = {
    apifoxProject: "1.0.0",
    $schema: {
      app: "apifox",
      type: "project",
      version: "1.2.0"
    },
    info: {
      name: "portal-server",
      description: "Koa Admin Template 接口定义，可直接导入 Apifox 使用。",
      mockRule: {
        rules: [],
        enableSystemRule: true
      }
    },
    apiCollection: [
      {
        name: "根目录",
        id: rootId,
        auth: {},
        securityScheme: {},
        parentId: 0,
        serverId: "",
        description: "",
        identityPattern: {
          httpApi: {
            type: "methodAndPath",
            bodyType: "",
            fields: []
          }
        },
        shareSettings: {},
        visibility: "SHARED",
        moduleId: 6509018,
        preProcessors: [{
          id: "inheritProcessors",
          type: "inheritProcessors",
          data: {}
        }],
        postProcessors: [{
          id: "inheritProcessors",
          type: "inheritProcessors",
          data: {}
        }],
        inheritPostProcessors: {},
        inheritPreProcessors: {},
        items: [
          authFolder,
          userFolder,
          permissionFolder,
          memberFolder,
          memberLevelFolder,
          backupFolder,
          healthFolder
        ]
      }
    ],
    socketCollection: [],
    docCollection: [],
    webSocketCollection: [],
    socketIOCollection: [],
    responseCollection: [],
    schemaCollection: [],
    securitySchemeCollection: [],
    requestCollection: [{
      name: "根目录",
      children: [],
      ordering: [],
      items: []
    }],
    environments: [],
    commonScripts: [],
    globalVariables: [{
      id: "7373537",
      variables: [{
        name: "Authorization",
        value: "",
        description: "Bearer Token",
        isBindInitial: true,
        initialValue: "",
        isSync: true
      }]
    }],
    commonParameters: null,
    projectSetting: {
      id: "7412823",
      auth: {},
      securityScheme: {},
      gateway: [],
      language: "zh-CN",
      apiStatuses: ["developing", "testing", "released", "deprecated"],
      mockSettings: {},
      preProcessors: [],
      postProcessors: [],
      advancedSettings: {
        enableJsonc: false,
        enableBigint: false,
        responseValidate: true,
        enableTestScenarioSetting: false,
        enableYAPICompatScript: false,
        isDefaultUrlEncoding: 2,
        publishedDocUrlRules: {
          defaultRule: "RESOURCE_KEY_ONLY",
          resourceKeyStandard: "NEW"
        }
      },
      initialDisabledMockIds: [],
      servers: [{
        id: "default",
        name: "默认服务"
      }],
      cloudMock: {
        security: "free",
        enable: false,
        tokenKey: "apifoxToken"
      }
    },
    customFunctions: [],
    projectTestCaseCategories: [
      {
        id: 3964804,
        name: "正向",
        description: "有效的输入和正确的预期结果，代表典型的用法。"
      },
      {
        id: 3964805,
        name: "负向",
        description: "消极的、无效的输入，如缺少字段、错误的类型、不支持的方法等。"
      },
      {
        id: 3964806,
        name: "边界值",
        description: "极端或边缘条件，如最大字符串长度、空值、零、null等"
      },
      {
        id: 3964807,
        name: "安全性",
        description: "可能暴露API安全性风险的测试用例。"
      },
      {
        id: 3964808,
        name: "其他",
        description: "其他未归属的测试用例。"
      }
    ],
    projectTestCaseTags: [
      {
        id: 7841994,
        name: "仅传必要字段",
        description: "仅发送具有有效值的必填字段，省略所有可选字段，以测试最小有效请求。"
      },
      {
        id: 7841995,
        name: "语义合法",
        description: "使用语法正确且在业务逻辑或域上下文中也有意义的值。"
      },
      {
        id: 7841996,
        name: "覆盖枚举组合",
        description: "对所有枚举型参数，应用正交设计系统地构建参数及其枚举值的测试用例组合，专用于测试枚举覆盖率"
      },
      {
        id: 7841997,
        name: "其他正向",
        description: "提供符合API规范的真实有效的输入，产生正确和预期的结果。"
      },
      {
        id: 7841998,
        name: "缺失必填字段",
        description: "在请求主体或参数中省略一个或多个必需字段。"
      },
      {
        id: 7841999,
        name: "无效值",
        description: "提供的值类型和格式正确，但在逻辑上对该字段无效。"
      },
      {
        id: 7842000,
        name: "类型错误",
        description: "使用数据类型不正确的值，例如发送字符串而不是整数。"
      },
      {
        id: 7842001,
        name: "格式错误",
        description: "以不正确的格式提供值，例如，错误的日期模式，格式错误的电子邮件地址。"
      },
      {
        id: 7842002,
        name: "语义非法",
        description: "使用语法正确且格式正确的值，这些值在逻辑上不可能或违反域规则。"
      },
      {
        id: 7842003,
        name: "其他负向",
        description: "提供无效或意外的输入，应触发错误处理或拒绝API。"
      },
      {
        id: 7842004,
        name: "Null",
        description: "必须是 JSON 字面量 `null`（不是空的，也不是 \"null\"）。"
      },
      {
        id: 7842005,
        name: "零值",
        description: "必须是数字字面值0。"
      },
      {
        id: 7842006,
        name: "空值",
        description: "必须是\"\"。"
      },
      {
        id: 7842007,
        name: "极大值",
        description: "Max/min值 - 为数字或日期字段提供精确的最小值和最大值。"
      },
      {
        id: 7842008,
        name: "极小值",
        description: "Max/min值 - 为数字或日期字段提供精确的最小值和最大值。"
      },
      {
        id: 7842009,
        name: "超出最大边界值",
        description: "过长/过短字符串 - 提供超出允许的最小或最大边界的值。"
      },
      {
        id: 7842010,
        name: "超出最小边界值",
        description: "过长/过短字符串 - 提供超出允许的最小或最大边界的值。"
      },
      {
        id: 7842011,
        name: "字符串过长",
        description: "超出范围的值 - 提供大于允许的最大长度或小于要求的最小长度的字符串。"
      },
      {
        id: 7842012,
        name: "字符串过短",
        description: "超出范围的值 - 提供大于允许的最大长度或小于要求的最小长度的字符串。"
      },
      {
        id: 7842013,
        name: "对象级别授权缺失",
        description: "对象级别授权缺失 - 用户在没有适当授权的情况下访问或操作数据对象。"
      },
      {
        id: 7842014,
        name: "访问控制",
        description: "基于角色、权限或属性来限制用户能访问哪些资源、能执行哪些操作"
      },
      {
        id: 7842015,
        name: "认证失败",
        description: "认证失败 - 认证薄弱、配置错误或被绕过，导致未授权访问。"
      },
      {
        id: 7842016,
        name: "SQL注入",
        description: "在输入字段中插入恶意SQL代码，测试是否存在SQL注入漏洞。"
      },
      {
        id: 7842017,
        name: "XSS注入",
        description: "注入JavaScript或HTML标签来测试跨站点脚本漏洞。"
      },
      {
        id: 7842018,
        name: "模糊输入",
        description: "发送大型或随机生成的有效载荷，以测试输入的有效性和稳定性。"
      },
      {
        id: 7842019,
        name: "命令行注入",
        description: "将shell命令插入输入以测试命令执行漏洞。"
      },
      {
        id: 7842020,
        name: "JSON注入",
        description: "插入恶意或意外的JSON结构来测试解析和验证。"
      },
      {
        id: 7842021,
        name: "NoSQL注入",
        description: "提供NoSQL特定的恶意查询或操作符来测试注入漏洞。"
      },
      {
        id: 7842022,
        name: "其他",
        description: "其他未归属的测试用例。"
      }
    ],
    projectAssociations: [],
    moduleSettings: [{
      id: "6509018",
      name: "默认模块",
      description: "",
      moduleVariables: [],
      openApiInfo: {}
    }]
  };

  return apifoxJson;
}

// 生成并保存文件
const apifoxJson = generateApifoxJson();
const outputPath = path.join(__dirname, '../doc/portal-server.Apifox.json');
fs.writeFileSync(outputPath, JSON.stringify(apifoxJson, null, 2), 'utf8');
console.log(`Apifox JSON 文件已生成: ${outputPath}`);

